package com.siashan.toolkit.oss.qiniu.core;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.siashan.toolkit.oss.core.OssResult;
import com.siashan.toolkit.oss.core.OssStorageService;
import com.siashan.toolkit.oss.core.enums.OssChannel;
import com.siashan.toolkit.oss.core.exception.ToolkitOssException;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 七牛云存储
 *
 * @author siashan
 * @since v1.0.1
 */
public class QiniuOssStorageService extends OssStorageService {
    private UploadManager uploadManager;
    private BucketManager bucketManager;
    private String token;
    private QiniuOssConfig config;

    /**
     * 构造方法
     */
    public QiniuOssStorageService() {
        config = new QiniuOssConfig();
        config.setAccessKey(QiniuOssConfiguration.getAccessKey());
        config.setBucketName(QiniuOssConfiguration.getBucketName());
        config.setDomain(QiniuOssConfiguration.getDomain());
        config.setPrefix(QiniuOssConfiguration.getPrefix());
        config.setSecretKey(QiniuOssConfiguration.getSecretKey());
        config.setRegion(QiniuOssConfiguration.getRegion());
        init();
    }

    /**
     * 构造方法
     *
     * @param config 七牛云配置
     */
    public QiniuOssStorageService(QiniuOssConfig config) {
        this.config = config;

        //初始化
        init();
    }

    /**
     * 初始化客户端
     */
    private void init() {
        Configuration cfg = new Configuration(QiniuOssRegionEnum.parseRegion(config.getRegion()));
        uploadManager = new UploadManager(cfg);
        token = Auth.create(config.getAccessKey(), config.getSecretKey()).uploadToken(config.getBucketName());
        initBucketManager(cfg);

    }

    private void initBucketManager(Configuration cfg) {
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        bucketManager = new BucketManager(auth, cfg);
    }

    /**
     * 文件上传
     * @param data    文件字节数组
     * @param path    文件路径，包含文件名
     * @return Oss上传结果
     */
    @Override
    public OssResult upload(byte[] data, String path) {
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
        } catch (Exception e) {
            throw new ToolkitOssException("上传文件失败，请核对七牛配置信息", e);
        }
        return OssResult.build(path,config.getDomain(), OssChannel.QINIU);
    }

    /**
     * 文件上传
     * @param inputStream   字节流
     * @param path          文件路径，包含文件名
     * @return Oss上传结果
     */
    @Override
    public OssResult upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new ToolkitOssException("上传文件失败", e);
        }
    }

    /**
     * 文件上传
     * @param data     文件字节数组
     * @param suffix   后缀
     * @return Oss上传结果
     */
    @Override
    public OssResult uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getPrefix(), suffix));
    }

    /**
     * 文件上传
     * @param inputStream  字节流
     * @param suffix       后缀
     * @return Oss上传结果
     */
    @Override
    public OssResult uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getPrefix(), suffix));
    }

    /**
     * 文件删除
     *
     * @param fileName  资源名称
     * @return 是否成功标识
     */
    @Override
    public boolean remove(String fileName) {
        try {
            Response delete = bucketManager.delete(config.getBucketName(), fileName);
        } catch (QiniuException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


}
